package com.yami.shop.live.multishop.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.enums.LiveInterfaceType;
import com.yami.shop.bean.enums.LiveRoomStatusType;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.CharUtil;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.live.common.constant.LiveConstant;
import com.yami.shop.live.common.model.LiveRoom;
import com.yami.shop.live.common.model.LiveRoomBack;
import com.yami.shop.live.common.param.LiveUsableNumParam;
import com.yami.shop.live.common.service.LiveLogService;
import com.yami.shop.live.common.service.LiveRoomBackService;
import com.yami.shop.live.common.service.LiveRoomProdService;
import com.yami.shop.live.common.service.LiveRoomService;
import com.yami.shop.security.multishop.util.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.collections4.CollectionUtils;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.Objects;


/**
 * @author lhd
 * @date 2020-08-05 08:53:17
 */
@RestController
@AllArgsConstructor
@RequestMapping("/multishop/live/liveRoom")
@Tag(name = "商家端直播间接口")
public class LiveRoomController {

    private final LiveRoomBackService liveRoomBackService;
    private final LiveRoomProdService liveRoomProdService;
    private final LiveRoomService liveRoomService;
    private final LiveLogService liveLogService;

    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('live:liveRoom:page')")
    @Operation(summary =  "分页查找直播间信息")
    public ServerResponseEntity<IPage<LiveRoom>> getLiveRoomPage(PageParam<LiveRoom> page,@ParameterObject LiveRoom liveRoom) {
        IPage<LiveRoom> roomPage = liveRoomService.page(page, new LambdaQueryWrapper<LiveRoom>()
                .eq(LiveRoom::getShopId, SecurityUtils.getShopUser().getShopId()).orderByDesc(LiveRoom::getUpdateTime)
                .eq(Objects.nonNull(liveRoom.getRoomTop()), LiveRoom::getRoomTop, liveRoom.getRoomTop())
                .like(StrUtil.isNotBlank(liveRoom.getName()), LiveRoom::getName, liveRoom.getName())
                .like(StrUtil.isNotBlank(liveRoom.getAnchorName()), LiveRoom::getAnchorName, liveRoom.getAnchorName())
                .eq(Objects.nonNull(liveRoom.getLiveStatus()), LiveRoom::getLiveStatus, liveRoom.getLiveStatus())
                .ge(Objects.nonNull(liveRoom.getStartTime()), LiveRoom::getStartTime, liveRoom.getStartTime())
                .le(Objects.nonNull(liveRoom.getStartTime()), LiveRoom::getStartTime, liveRoom.getEndTime())
                .orderByDesc(LiveRoom::getStartTime));
        if (CollectionUtils.isNotEmpty(roomPage.getRecords())) {
            for (LiveRoom liveRoomDb : roomPage.getRecords()) {
                LiveRoom.RoomToolsVO roomToolsVO = JSON.parseObject(liveRoomDb.getRoomTools(), LiveRoom.RoomToolsVO.class);
                liveRoomDb.setRoomToolsVo(roomToolsVO);
            }
        }
        return ServerResponseEntity.success(roomPage);
    }

    @GetMapping("/info/{id}")
    @Operation(summary =  "通过id查询直播间")
    @Parameter(name = "id", description = "直播间id", required = true)
    public ServerResponseEntity<LiveRoom> getById(@PathVariable("id") Long id) {
        LiveRoom liveRoomDb = liveRoomService.getById(id);
        if (!Objects.equals(SecurityUtils.getShopUser().getShopId(), liveRoomDb.getShopId())) {
            throw new YamiShopBindException("yami.no.auth");
        }
        LiveRoom.RoomToolsVO roomToolsVO = JSON.parseObject(liveRoomDb.getRoomTools(), LiveRoom.RoomToolsVO.class);
        liveRoomDb.setRoomToolsVo(roomToolsVO);
        return ServerResponseEntity.success(liveRoomDb);
    }

    @GetMapping("/getPlayBack/{id}")
    @Operation(summary =  "通过id查询直播间回放信息")
    @Parameter(name = "id", description = "直播间id", required = true)
    public ServerResponseEntity<LiveRoomBack> getPlayBackByRoomId(@PathVariable("id") Long id) {
        return ServerResponseEntity.success(liveRoomBackService.getOne(new LambdaQueryWrapper<LiveRoomBack>().eq(LiveRoomBack::getRoomId, id)));
    }

    @PostMapping
    @PreAuthorize("@pms.hasPermission('live:liveRoom:save')")
    @Operation(summary =  "新增直播间")
    public ServerResponseEntity<Boolean> save(@RequestBody @Valid LiveRoom liveRoom) throws WxErrorException {
        if (CharUtil.length(liveRoom.getName()) < LiveConstant.ROOM_NAME_MIN_LENGTH || CharUtil.length(liveRoom.getName()) > LiveConstant.ROOM_NAME_MAX_LENGTH) {
            // 直播间名称长度非法,最短3个汉字，最长17个汉字！
            throw new YamiShopBindException("yami.live.room.name.check");
        }
        if (CharUtil.length(liveRoom.getAnchorName()) < LiveConstant.USER_NAME_MIN_LENGTH || CharUtil.length(liveRoom.getAnchorName()) > LiveConstant.USER_NAME_MAX_LENGTH) {
            // 主播昵称长度非法，最短2个汉字，最长15个汉字
            throw new YamiShopBindException("yami.live.room.name.check2");
        }
        liveRoom.setShopId(SecurityUtils.getShopUser().getShopId());
        liveRoom.setUpdateTime(new Date());
        liveRoom.setApplyTime(new Date());
        liveRoom.setLiveStatus(LiveRoomStatusType.NO_START.value());
        liveRoomService.saveLiveRoom(liveRoom);
        return ServerResponseEntity.success();
    }

    @PostMapping("/addLiveRoomProd")
    @Operation(summary =  "新增直播间商品")
    public ServerResponseEntity<Boolean> addLiveRoomProd(@RequestBody @Valid LiveRoom liveRoom) throws WxErrorException {
        liveRoom.setShopId(SecurityUtils.getShopUser().getShopId());
        liveRoomProdService.saveBatchAndRoomId(liveRoom);
        return ServerResponseEntity.success();
    }

    @GetMapping("/getAddRoomNum")
    @Operation(summary =  "查询商家今日剩余可用添加直播间次数")
    public ServerResponseEntity<LiveUsableNumParam> getAddRoomNum() {
        LiveUsableNumParam liveNum = liveLogService.getLiveNum(SecurityUtils.getShopUser().getShopId(), LiveInterfaceType.CREATE_ROOM);
        LiveUsableNumParam deleteLiveNum = liveLogService.getLiveNum(SecurityUtils.getShopUser().getShopId(), LiveInterfaceType.REMOVE_LIVE_ROOM);
        liveNum.setDeleteShopNum(deleteLiveNum.getShopNum());
        liveNum.setDeleteTotalNum(deleteLiveNum.getTotalNum());
        return ServerResponseEntity.success(liveNum);
    }

    @DeleteMapping("/{id}")
    @Operation(summary =  "通过id删除直播间信息")
    @Parameter(name = "id", description = "直播间id", required = true)
    public ServerResponseEntity<Boolean> removeById(@PathVariable Long id) throws WxErrorException {
        return ServerResponseEntity.success(liveRoomService.removeRoomById(id, SecurityUtils.getShopUser().getShopId()));
    }
}
